package com.bjsxt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**单向通信：通信双方中，一方固定为发送端，一方则固定为接收端
        * 创建服务端*/
public class OnewaySocketServer02 {
    public static void main(String[] args) {
        Socket socket = null;
        PrintWriter pw = null;
        BufferedReader br = null;
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("开始监听端口...");
            socket = serverSocket.accept();//accept()返回的是socket的字符串信息
            System.out.println("连接成功");
            //读取客户端发送来的信息   InputStreamReader字节转字符
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //向客户端写回消息的流对象
            pw = new PrintWriter(socket.getOutputStream());
            //服务端一直等待客户端发送消息  所以用无限循环
            while (true){
                String str = br.readLine();
                System.out.println("客户端说："+str);
                if("exit".equals(str)){
                    break;
                }
                //在服务端中，将信息返回客户端
                pw.println(str);
                pw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
